//
//  YRUserAccount.swift
//  YR 微博
//
//  Created by cyr on 15/10/13.
//  Copyright © 2015年 cyr. All rights reserved.
//

import UIKit

class YRUserAccount: NSObject,NSCoding{

 /// 用户是否登陆标记
    class var userLogon:Bool {
        return sharedAccount != nil
    }
    
    /**
    用于调用access_token，接口获取授权后的access token
    */
    var access_token: String?
    
    /**
    string	access_token的生命周期，单位是秒数
    */
    var expires_in: NSTimeInterval = 0
    
    /**
    token 过期日期
    */
    var expiresDate: NSDate?
    
    /**
    当前授权用户的UID
    */
    var uid: String?
    
    /**
    静态的用户账户属性
    */
    static var userAccount: YRUserAccount?
    
    /**
    好友显示名称
    */
    var name: String?
    
    /**
    用户头像地址(180*180)
    */
    var avatar_large: String?
    
    
    
    init(dict: [String: AnyObject]) {
        super.init()
        
        setValuesForKeysWithDictionary(dict)
        
        // 设置全局的用户信息
        YRUserAccount.userAccount = self
        
        expiresDate = NSDate(timeIntervalSinceNow: expires_in)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
   
    override var description: String {
    
        let properties = ["access_token","expires_in","uid","expiresDate"]
        
        return "\(dictionaryWithValuesForKeys(properties))"
    }
    
    //
    func loadUserInfo(finished: (error: NSError?) ->()) {
        YRNetworkTools.sharedTools.loadUserInfo(uid!) { (result, error) -> () in
            if error != nil {
                finished(error: error)
                return
            }
            
            
            // 设置用户信息
            self.name = result!["name"] as? String
            self.avatar_large = result!["avatar_large"] as? String
            
            // 保存用户信息
            self.saveAccount()
            
            //完成回调
            finished(error: nil)
        }
    }
    
    
    
    // MARK: -加载用户信息
    class var sharedAccount: YRUserAccount? {
        
        if userAccount == nil {
            
       userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? YRUserAccount
            
        }
//            判断 token 是否过期

        if let date = userAccount?.expiresDate where date.compare(NSDate()) == NSComparisonResult.OrderedAscending {
            // 如果已经过期，需要清空账号记录
            userAccount = nil
        }
      return userAccount
    }
    
    // MARK: -解档&归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token,forKey:"access_token")
        aCoder.encodeObject(expires_in,forKey: "expires_in")
        aCoder.encodeObject(expiresDate,forKey:"expiresDate")
        aCoder.encodeObject(uid,forKey:"uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = (aDecoder.decodeObjectForKey("expires_in") as? NSTimeInterval)!
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large")  as? String
    }
    // 保存文件的路径
    static private let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask,true).last!.stringByAppendingString("/account.plist")
    
    // 保存账户信息
    func saveAccount() {
        NSKeyedArchiver.archiveRootObject(self, toFile: YRUserAccount.accountPath)
    }
    
}
